<template>
	<view class="classify-container">
		<!-- 搜索框 -->
		<view class="search-section">
			<view class="search-box" @click="go('/subPackages/home/search/search')">
				<image src="/static/classify/classify_search.png" class="search-icon"></image>
				<text class="search-placeholder">搜索</text>
			</view>
		</view>

		<!-- 筛选标签 -->
		<view class="filter-section">
			<view class="filter-tabs">
				<view class="filter-tab active" @click="selectTab('comprehensive')">
					<text class="filter-text" :class="{active: activeTab === 'comprehensive'}">综合</text>
				</view>
				<view class="filter-tab" @click="selectTab('sales')">
					<text class="filter-text" :class="{active: activeTab === 'sales'}">销量</text>
				</view>
				<view class="filter-tab" @click="selectTab('price')">
					<text class="filter-text" :class="{active: activeTab === 'price'}">价格</text>
					<image :src="price_img" class="price-image"></image>
				</view>
			</view>
		</view>

		<!-- 主要内容区域 -->
		<view class="main-content">
			<!-- 左侧城市列表 -->
			<view class="city-list">
				<scroll-view scroll-y="true" class="city-scroll">
					<view 
						class="city-item" 
						:class="{
							active: selectedCity === index,
							'top-rounded': selectedCity === index + 1,
							'bottom-rounded': selectedCity === index - 1
						}"
						v-for="(city, index) in cityList" 
						:key="index"
						@click="selectCity(index,city)"
					>
						<text class="city-name">{{ city.area }}</text>
					</view>
				</scroll-view>
			</view>

			<!-- 右侧商品列表 -->
			<view class="product-list" v-if="productList.length > 0">
				<scroll-view scroll-y="true" class="product-scroll">
					<view class="product-item" v-for="(product, index) in productList" :key="index" @click="goToDetail(product)">
						<view class="product-card">
							<view class="product-image-container">
								<image :src="product.mainImage" class="product-image"></image>
							</view>
							<view class="product-info">
								<view class="product-title">
									<image class="product-tag" src="/static/hot.png" v-if="product.isHot === 'Y'"></image>
									<image class="product-tag" src="/static/sale.png" v-if="product.isSpecial === 'Y'"></image>
									<image class="product-tag" src="/static/new.png"  v-if="product.isNew === 'Y'"></image>
									<text class="product-name">{{ product.title }}</text>
								</view>
								<view class="product-location">
									<image src="/static/classify/classify_address.png" class="location-icon"></image>
									<text class="location-text">{{ product.area }}</text>
								</view>
								<view class="product-price">
									<text class="current-price">¥{{ product.price }}</text>
									<text class="current-unit">{{ product.unit }}</text>
									<text class="original-price" v-if="product.underlinePrice">¥{{ product.underlinePrice }}</text>
								</view>
							</view>
							<view class="add-btn">
								<image :id="`classify-add-${index}`" src="/static/classify/classify_add.png" class="add-icon" @tap.stop="addProductWithAnimation(product, $event, 'classify', index)"></image>
							</view>
						</view>
					</view>
				</scroll-view>
			</view>
			<view class="product-list" v-else>
				<view class="product-no-list">
					<image class="no-product-car" src="/static/no-car.png"></image>
					<text class="no-product-text">暂无商品</text>
				</view>
			</view>
		</view>
		
		<!-- 购物车动画元素 -->
		<view class="cart-animation-container">
			<view 
				v-for="(ball, index) in animationBalls" 
				:key="index"
				v-show="ball.show"
				class="cart-ball"
				:style="{
					left: ball.startX + 'px',
					top: ball.startY + 'px',
					transform: `translate(${ball.translateX}px, ${ball.translateY}px)`,
					transition: ball.transition
				}"
			>
				<image src="/static/classify/classify_add.png" class="ball-icon"></image>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				activeTab: 'comprehensive', // 当前选中的tab
				priceOrder: 'asc',
				price_img:'/static/fitter_1.png',
				selectedCity: 0,
				curAreaId:null,
				priceOrder: 'asc',
				cityList: [],
				productList: [],
				// 动画相关数据
				animationBalls: [],
				maxBalls: 50, // 最大同时动画数量
			}
		},
		onLoad() {
			this.requestProductAllGroup()
		},
		onShow() {
			if (uni.getStorageSync('token')) {
				//请求购物车商品
				this.requestCartList()
			} else {
				// 未登录时清空购物车角标
				this.clearCartCount();
			}
		},
		methods: {
			//请求购物车商品
			requestCartList() {
				let that = this
				that.https({
					method: "GET",
					url: '/project/order/listCart',
					success: res => {
					console.log("res CartList-------- ", res)
					if (res.code == 200) {
						// 更新购物车角标数量
						const totalCount = res.rows[0].details.reduce((total, item) => {
							return total + (item.productNum || 0);
						}, 0);
						that.setCartCount(totalCount);
					} else {
						// 购物车为空时清空角标
						that.clearCartCount();
					}
				},
					fail: err => {},
					complete: com => {}
				})
			},
			//请求商品所有分组
			requestProductAllGroup(){
				let that = this
				that.https({
					method: "GET",
					url: '/project/product/queryAllGroup/area',
					success: res => {
						console.log("res -------- ", res)
						if (res.code == 200) {
							that.cityList = res.data
							that.curAreaId = res.data[0].areaId
							that.requestProductList(res.data[0].areaId)
						}
					},
					fail: err => {},
					complete: com => {}
				})
			},
			//请求商品
			requestProductList(areaId){
				this.curAreaId = areaId
				let that = this
				let data;
				if (that.activeTab === 'sales') {
					data = {
						orderByColumn: "saleNum",
						// productType:1,
						areaId:areaId
					}
				} else if (that.activeTab === 'price') {
					data = {
						isAsc: that.priceOrder,
						orderByColumn: "price",
						// productType:1,
						areaId:areaId
					}
				} else {
					data = {
						// productType: 2,
						areaId:areaId
					}
				}
				that.https({
					method: "GET",
					url: '/project/product/list',
					data:data,
					success: res => {
						console.log("res -------- ", res)
						if (res.code == 200) {
							that.productList = res.rows
						}
					},
					fail: err => {},
					complete: com => {}
				})
			},
			//添加商品
			addProduct(item){
				console.log(" add product ===== ",item)
				let that = this
				const orderData = {
					orderType: 1,
					details: [{
						productId: item.id,
						mainImage: item.mainImage,
						productTitle: item.title,
						productPrice: item.price,
						productNum: 1,
						unit:item.unit,
						areaAddr:item.area,
					}],
				}
				that.https({
					method: "POST",
					url: '/project/order/editCart',
					data: orderData,
					success: res => {
						if (res.code == 200) {
							uni.showToast({
								title: '已添加到购物车',
								icon: 'success'
							});
							console.log("res addProduct -----  ", res)
							// 增加购物车角标数量
							that.addCartCount(1);
						}
					},
					fail: err => {},
					complete: com => {}
				})
			},
			selectCity(index,item) {
				this.selectedCity = index;
				this.requestProductList(item.areaId)
			},
			//tab点击
			selectTab(tab) {
				this.activeTab = tab;
				if (tab === 'price') {
					// 切换价格排序
					if (this.priceOrder === 'default') {
						this.priceOrder = 'asc';
						this.price_img = '/static/fitter_3.png';
					} else if (this.priceOrder === 'asc') {
						this.priceOrder = 'desc';
						this.price_img = '/static/fitter_2.png';
					} else {
						this.price_img = '/static/fitter_3.png';
						this.priceOrder = 'asc';
					}
				}
				this.requestProductList(this.curAreaId)
			},
			goToDetail(item) {
				this.go(`/subPackages/classify/goodsDetail/goodsDetail?id=${item.id}`)
			},
			
			// 带动画的添加商品方法
			addProductWithAnimation(item, event, type, index) {
				// 添加点击反馈效果
				const elementId = `${type}-add-${index}`;
				const query = uni.createSelectorQuery().in(this);
				
				// 给按钮添加点击效果
				query.select(`#${elementId}`).fields({
					node: true
				}, (res) => {
					if (res && res.node) {
						// 添加点击缩放效果
						res.node.style.transform = 'scale(0.9)';
						res.node.style.transition = 'transform 0.1s';
						
						setTimeout(() => {
							res.node.style.transform = 'scale(1)';
						}, 100);
					}
				}).exec();
				
				// 先执行添加商品逻辑
				this.addProduct(item);
				
				// 执行动画
				this.startCartAnimation(event, type, index);
			},
			
			// 开始购物车动画
			startCartAnimation(event, type, index) {
				// 限制同时动画数量
				if (this.animationBalls.length >= this.maxBalls) {
					return;
				}
				
				// 获取点击按钮的位置
				const elementId = `${type}-add-${index}`;
				const query = uni.createSelectorQuery().in(this);
				
				query.select(`#${elementId}`).boundingClientRect((rect) => {
					if (rect) {
						// 获取购物车选项卡位置（底部第4个选项卡）
						const systemInfo = uni.getSystemInfoSync();
						const tabBarHeight = 80; // tabBar高度（rpx转px）
						const safeAreaBottom = systemInfo.safeAreaInsets ? systemInfo.safeAreaInsets.bottom : 0;
						// 购物车是第4个选项卡（索引3），每个选项卡占1/5宽度，购物车在3/5位置
						const cartTabPosition = {
							x: systemInfo.windowWidth * 0.68, // 第4个选项卡位置
							y: systemInfo.windowHeight - safeAreaBottom + 30
						};
					
						// 创建动画球
						const ball = {
							show: true,
							startX: rect.left + rect.width / 2,
							startY: rect.top + rect.height / 2,
							translateX: 0,
							translateY: 0,
							transition: 'none'
						};
						
						this.animationBalls.push(ball);
						
						// 延迟启动动画
						this.$nextTick(() => {
							setTimeout(() => {
								// 计算目标位置
								const targetX = cartTabPosition.x - ball.startX;
								const targetY = cartTabPosition.y - ball.startY;
								
								// 设置动画 - 使用抛物线效果
								ball.translateX = targetX;
								ball.translateY = targetY;
								ball.transition = 'all 1.0s cubic-bezier(0.17, 0.67, 0.35, 0.35)';
								
								// 动画结束后清理
								setTimeout(() => {
									ball.show = false;
									// 从数组中移除
									const ballIndex = this.animationBalls.indexOf(ball);
									if (ballIndex > -1) {
										this.animationBalls.splice(ballIndex, 1);
									}
								}, 1000);
							}, 50);
						});
					}
				}).exec();
			}
		}
	}
</script>

<style lang="scss">
	.classify-container {
		background-color: #f5f5f5;
		height: 100vh;
		display: flex;
		flex-direction: column;
	}

	/* 搜索框 */
	.search-section {
		padding: 20rpx 30rpx;
		background: white;
		.search-box {
			background: #f5f5f5;
			border-radius: 16rpx;
			padding: 10px 15px;
			display: flex;
			align-items: center;
			justify-content: center;
			.search-icon {
				width: 16px;
				height: 16px;
				margin-right: 8px;
			}
			
			.search-placeholder {
				color: #999;
				font-size: 14px;
			}
		}
	}
	/* 筛选标签 */
	.filter-section {
		padding: 20rpx 30rpx;
		background-color: #fff;
		border-bottom: 1px solid #f0f0f0;
		.filter-tabs {
			display: flex;
			// margin: 0 40rpx 0 60rpx;
			justify-content: space-between;
			
			.filter-tab {
				flex: 1;
				display: flex;
				align-items: center;
				justify-content: center;
				position: relative;
				
				.filter-text {
					text-align: center;
					font-size: 14px;
					color: #666;
				}
				
				.filter-text.active {
					color: #009966;
					font-size: 28rpx;
				}
				.price-image {
					width: 36rpx;
					height: 36rpx;
				}
			}
		}
	}


	/* 主要内容区域 */
	.main-content {
		flex: 1;
		display: flex;
		overflow: hidden;
	}

	/* 左侧城市列表 */
	.city-list {
		width: 100px;
		background: #fff;
		
		.city-scroll {
			height: 100%;
			.city-item {
				padding: 15px 10px;
				background-color: #F2F9F7;
				text-align: center;
			}
			
			.city-item.active {
				background: white;
				position: relative;
			}
			
			/* 选中项上方的城市项添加下圆角 */
			.city-item.bottom-rounded {
				border-top-right-radius: 24rpx;
			}
			
			/* 选中项下方的城市项添加上圆角 */
			.city-item.top-rounded {
				border-bottom-right-radius: 24rpx;
			}
			
			.city-item.active::before {
			  content: "";
			  position: absolute;
			  left: 0;
			  top: 20rpx;     /* 上间距 */
			  bottom: 20rpx;  /* 下间距 */
			  width: 4rpx;
			  background-color: #009966;
			}
			
			.city-item.active .city-name {
				color: #009966;
				font-weight: bold;
			}
			
			.city-name {
				font-size: 12px;
				color: #666;
			}
		}
	}

	/* 右侧商品列表 */
	.product-list {
		flex: 1;
		background: white;
		.product-scroll {
			height: 100%;
			.product-item {
				.product-card {
					display: flex;
					background: white;
					border-radius: 8rpx;
					padding: 16rpx;
					position: relative;
					.product-image-container {
						position: relative;
						margin-right: 15rpx;
						.product-image {
							width: 160rpx;
							height: 160rpx;
							border-radius: 12rpx;
						}
					}
					.product-info {
						flex: 1;
						.product-title {
							display: flex;
							align-items: center;
							/* 两行文本溢出省略 */
							display: -webkit-box;
							-webkit-box-orient: vertical;
							-webkit-line-clamp: 2;
							overflow: hidden;
							text-overflow: ellipsis;
							.product-tag {
								width: 64rpx;
								height: 28rpx;
								margin-right: 8rpx;
							}
							.product-name {
								font-size: 32rpx;
								color: #333;
								font-weight: bold;
							}
						}
						.product-location {
							display: flex;
							align-items: center;
							margin-bottom: 8px;
							.location-icon {
								width: 12px;
								height: 12px;
								margin-right: 4px;
							}
							.location-text {
								font-size: 12px;
								color: #999;
							}
						}
					}
				}
			}
		}
		.product-no-list {
			display: flex;
				flex-direction: column;
				align-items: center;
				justify-content: center;
				padding: 150rpx 0;
				.no-product-car {
					width: 360rpx;
					height: 360rpx;
				}
				.no-product-text {
					font-family: PingFang SC, PingFang SC;
					font-weight: 500;
					font-size: 28rpx;
					color: #333333;
					line-height: 42rpx;
					text-align: center;
				}
			}
	}

	.product-price {
		display: flex;
		align-items: center;
	}

	.current-price {
		font-size: 16px;
		color: #FF6B35;
		font-weight: bold;
	}
	.current-unit {
		font-family: PingFang SC, PingFang SC;
		font-weight: 500;
		font-size: 28rpx;
		color: #333333;
		text-align: left;	
	}

	.original-price {
		font-size: 12px;
		color: #999;
		text-decoration: line-through;
	}

	.add-btn {
		position: absolute;
		bottom: 15px;
		right: 15px;
		width: 24px;
		height: 24px;
	}

	.add-icon {
		width: 100%;
		height: 100%;
	}

	/* 底部导航栏 */
	.bottom-nav {
		background: white;
		display: flex;
		border-top: 1px solid #f0f0f0;
		padding-bottom: env(safe-area-inset-bottom);
	}

	.nav-item {
		flex: 1;
		display: flex;
		flex-direction: column;
		align-items: center;
		padding: 8px 0;
	}

	.nav-item.active .nav-text {
		color: #00C896;
	}

	.nav-icon {
		width: 24px;
		height: 24px;
		margin-bottom: 4px;
	}

	.nav-text {
		font-size: 10px;
		color: #999;
	}
	/* 购物车动画样式 */
	.cart-animation-container {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		pointer-events: none;
		z-index: 9999;
	}
	
	.cart-ball {
		position: absolute;
		width: 48rpx;
		height: 48rpx;
		z-index: 10000;
		pointer-events: none;
		
		.ball-icon {
			width: 100%;
			height: 100%;
			border-radius: 50%;
			box-shadow: 0 6rpx 20rpx rgba(0, 153, 102, 0.4);
			background: rgba(255, 255, 255, 0.9);
			border: 2rpx solid #009966;
			animation: ballFloat 1.0s ease-out;
		}
	}
	
	@keyframes ballFloat {
		0% {
			transform: rotate(0deg) scale(1);
			opacity: 1;
			box-shadow: 0 6rpx 20rpx rgba(0, 153, 102, 0.4);
		}
		25% {
			transform: rotate(90deg) scale(1);
			opacity: 0.9;
			box-shadow: 0 8rpx 25rpx rgba(0, 153, 102, 0.5);
		}
		50% {
			transform: rotate(180deg) scale(1);
			opacity: 0.8;
			box-shadow: 0 10rpx 30rpx rgba(0, 153, 102, 0.6);
		}
		75% {
			transform: rotate(270deg) scale(1.0);
			opacity: 0.7;
			box-shadow: 0 8rpx 25rpx rgba(0, 153, 102, 0.5);
		}
		100% {
			transform: rotate(360deg) scale(1.0);
			opacity: 0.3;
			box-shadow: 0 4rpx 15rpx rgba(0, 153, 102, 0.3);
		}
	}
</style>
